#!/usr/bin/python
# -*- coding:utf-8 -*-
import socket
import serial
import Queue
from threading import Thread

ser = serial.Serial("/dev/ttyUSB0",115200)
qBuffer = Queue.Queue()
HOST_IP = "192.168.2.160"  
HOST_PORT = 4001
socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
##socket_tcp.connect(("192.168.2.160",4001))
print("TCP server listen @ %s:%d!" %(HOST_IP, HOST_PORT))
host_addr=(HOST_IP,HOST_PORT)
socket_tcp.bind(host_addr)
socket_tcp.listen(1)
socket_con, (client_ip, client_port) = socket_tcp.accept()
print("Connection accepted from %s." %client_ip) # PC IP
#print('serial test start ...')

def getData(): # 从 arduino或者 STM32 串口拿数据
    while True:
        try:
            data = ser.read()
            qBuffer.put(data)
        except KeyboardInterrupt:
            if ser != None:
                ser.close()
def sendToPC(): # 往PC发数据
    while True:
        try:
            send = qBuffer.get()
            #print(send)
            socket_con.send(send)
        except:
            socket_tcp.close()
        
try:
   t1 = Thread(target=getData)
   t2 = Thread(target=sendToPC)
   t1.start()
   t2.start()
except:
   print (b"Error: unable to start thread")


        

